package mysql.uitl;

import mysql.res;

import javax.xml.transform.Result;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class mysqlUtil {
    static String DRIVER;
    static String URL;
    static String USERNAME;
    static String PASSWORD;
    static Connection connection=null;
    static PreparedStatement ps = null;
    static ResultSet rs=null;
    static {
        try {
            //用来操作配置文件当中的信息
            Properties properties = new Properties();
            //反射去加载配置文件
            InputStream is = res.class.getClassLoader().getResourceAsStream("mysql.properties");
            //使用properties对象加载输入流
            properties.load(is);
            DRIVER = properties.getProperty("driver");
            URL = properties.getProperty("url");
            USERNAME = properties.getProperty("username");
            PASSWORD = properties.getProperty("password");
            Class.forName(DRIVER);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static Connection getConn(){
        try {
            connection = DriverManager.getConnection(URL,
                    USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }
    //    执行器
    public static PreparedStatement getPs(String sql){
        try {
            ps = connection.prepareStatement(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return ps;
    }
    public static ResultSet getRs() {
        try {
            rs = ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }

    //增删改
    public static int getInsert() {
        int i = 0;
        try {
            i = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }
    public static void close(){
        //conn ps rs
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (ps!=null){
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (connection!=null){
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
